<?php

namespace App\Dao;

use App\Exceptions\SysExceptions;
use App\Model\ShopsModel;
use App\Services\DouFuServices;

class ShopsDao extends BaseDao
{
    public static function get_builder_query($params = []){
        $query = ShopsModel::query();

        $query->when(checkIsHasField($params,'shop_id'),function ($query)use ($params){
            $query->where('shop_id',$params['shop_id']);
        });


        $query->when(checkIsHasField($params,'status'),function ($query)use ($params){
            $query->where('status',$params['status']);
        });

        $query->when(checkIsHasField($params,'shop_laike_id'),function ($query)use ($params){
            $query->where('shop_laike_id',$params['shop_laike_id']);
        });

        return $query;
    }

    public static function get_shop_pager($params = []){
        return self::get_builder_query($params)->paginate();
    }

    public static function get_one($params = []){
        return self::get_builder_query($params)->first();
    }

    /**
     * @throws SysExceptions
     */
    public static function add_shop($params = []){
        if(!in_array($params['shop_type'],[1,2])){
            self::error('抽佣类型不正确');
        }
        if($params['shop_value_yong'] > 1){
            self::error('抽佣比例不正确');
        }
        if(self::get_builder_query()->create($params) === false){
            self::error('添加失败');
        }
    }

    public static function laike_shop(array $all)
    {
        if(self::get_builder_query([
            'shop_id'=>$all['shop_id']
        ])->update([
            'shop_laike_id'=>$all['shop_laike_id']
        ]) === false){
            self::error('绑定失败');
        }
        $info = self::get_one([
            'shop_id'=>$all['shop_id']
        ]);
        //来客接口调用
        DouFuServices::shop_add([
            'account_id'=>$info['shop_laike_id'],
            'shop_type'=>$info['shop_type'],
            'shop_value_yong'=>$info['shop_value_yong'],
        ]);
    }

    public static function edit_shop(array $params)
    {
        if(!in_array($params['shop_type'],[1,2])){
            self::error('抽佣类型不正确');
        }

        if(self::get_builder_query([
            'shop_id'=>self::deleteParamId($params,'shop_id')
        ])->update(self::filterFields($params,new ShopsModel())) === false){
            self::error('修改失败');
        }
    }

    public static function updateStatus($content)
    {
        self::get_builder_query([
            'shop_laike_id'=>$content['merchant_id']
        ])->update([
            'status'=>$content['status']
        ]);
    }

}
